<?php

namespace framework\libraries;

use Exception;
use framework\support\Middleware;
use framework\support\Response;

class Controller
{

    function __construct()
    {
        if ($this->_before() === false) {
            throw new Exception("中间件拦截");
        }
    }


    protected function data($name, $value)
    {
        return request()->data($name, $value);
    }


    protected function  get($name, $default = null)
    {
        return request()->get($name, $default);
    }


    protected function  post($name = null, $default = null)
    {
        if (!$name) {
            return request()->post();
        } else {
            return request()->post($name, $default);
        }
    }


    protected function  file($name)
    {
        return request()->file($name);
    }

    protected function  rawBody()
    {
        return request()->rawBody();
    }

    protected function  getRealIp()
    {
        return request()->getRealIp();
    }


    protected function  isAjax()
    {
        return request()->isAjax();
    }

    protected function  server($name, $default = null)
    {
        return request()->server($name, $default);
    }


    protected function  header($name, $value = null)
    {
        return request()->header($name, $value);
    }


    protected function  success($data = null)
    {
        Response::success($data ?? []);
        $this->_after();
    }


    protected function  error($code, $msg = null, $data = null)
    {
        Response::error($code, $msg, $data);
        $this->_after();
    }


    protected function  redirect($url)
    {
        $this->_after();
        Response::Redirect($url);
    }

    protected function rawOutput($httpCode, $data = null)
    {
        $this->_after();
        Response::raw($httpCode, $data);
    }

    function _before()
    {
        $request = request();
        $route = $request->data('route');
        $middleware = Middleware::getInstance();
        return $middleware->before($route);
    }

    function _after()
    {
        $request = request();
        $route = $request->data('route');
        $middleware = Middleware::getInstance();
        return $middleware->after($route);
    }
}
